package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.BackendMemberDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.User;
import com.itheima.service.BackendMemberService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author Lz
 * @date 2020-03-08 10:21
 * @week 星期日
 */
@Service(interfaceClass = BackendMemberService.class)
@Transactional
public class BackendMemberServiceImpl implements BackendMemberService {
    @Autowired
    private BackendMemberDao backendMemberDao;

    private Pattern telephonePattern = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) throws Exception {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        if (currentPage == null || currentPage <= 0) {
            currentPage = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 1;
        }
        PageHelper.startPage(currentPage, pageSize);

        Page<Member> page = backendMemberDao.findPage(queryString);
        long total = page.getTotal();
        List<Member> members = page;
        List<Map> rows = new ArrayList<>();
        for (Member member : members) {
            Map map = new HashMap();
            Date birthday = member.getBirthday();
            if (birthday != null) {
                int birthYear = birthday.getYear();
                int nowYear = new Date().getYear();
                map.put("age", nowYear - birthYear);
            }

            map.put("id", member.getId());
            map.put("fileNumber", member.getFileNumber());
            map.put("name", member.getName());
            map.put("sex", member.getSex());
            String regTime = new SimpleDateFormat("yyyy-MM-dd").format(member.getRegTime());
            map.put("regTime", regTime);
            map.put("phoneNumber", member.getPhoneNumber());

            Integer id = member.getId();
            //根据id查询健康管理师
            User user = backendMemberDao.findUserByMemberId(id);
            map.put("healthManager",(user.getUsername()));
            rows.add(map);
        }
        return new PageResult(total, rows);
    }

    @Override
    public List<User> findAllHealthManaget() {
        List<User> users = backendMemberDao.findAllHealthManager();
        return users;
    }

    @Override
    public Result add(Map<String, Object> map) throws Exception {
        String name = (String) map.get("name");
        String phoneNumber = (String) map.get("phoneNumber");
        String sex = (String) map.get("sex");
        Date birthday = DateUtils.parseString2Date((String)map.get("birthday"));
        Integer healthManagerId = (Integer) map.get("healthManagerId");
        String idCard = (String) map.get("idCard");
        String fileNumber = (String) map.get("fileNumber");
        String remark = (String) map.get("remark");

        if (!telephonePattern.matcher(phoneNumber).matches()) {
            return new Result(false, "手机号校验不通过");
        }
        if (idCard.length() != 18) {
            return new Result(false, "身份证号校验失败");
        }
        Member member = new Member();
        if (name != null && name.length() > 0) {
            member.setName(name);
        }
        if (phoneNumber != null && phoneNumber.length() > 0) {
            member.setPhoneNumber(phoneNumber);
        }
        if (sex != null && sex.length() > 0) {
            member.setSex(sex);
        }
        if (birthday != null) {
            member.setBirthday(birthday);
        }
        if (idCard != null && idCard.length() > 0) {
            member.setIdCard(idCard);
        }
        if (fileNumber != null && fileNumber.length() > 0) {
            member.setFileNumber(fileNumber);
        }
        if (remark != null && remark.length() > 0) {
            member.setRemark(remark);
        }
        member.setRegTime(new Date());
        backendMemberDao.add(member);

        if (healthManagerId != null && healthManagerId > 0) {
            //添加会员与健康管理师的联系数据
            Integer memberId = member.getId();
            backendMemberDao.addMemberAndUser(memberId, healthManagerId);
        }

        return new Result(true, "新增会员信息成功");
    }

    @Override
    public Map findById(Integer id) {
        Map map = backendMemberDao.findById(id);
        return map;
    }

    @Override
    public Result edit(Map<String, Object> map) throws Exception {
        String phoneNumber = (String) map.get("phoneNumber");
        String idCard = (String) map.get("idCard");

        if (!telephonePattern.matcher(phoneNumber).matches()) {
            return new Result(false, "手机号校验不通过");
        }
        if (idCard.length() != 18) {
            return new Result(false, "身份证号校验失败");
        }

        //修改member信息
        backendMemberDao.edit(map);

        Integer healthManagerId = (Integer) map.get("healthManagerId");
        Integer id = (Integer) map.get("id");
        //修改会员和健康管理师的关联信息
        backendMemberDao.editMemberAndUser(healthManagerId, id);

        return new Result(true, "修改会员信息成功");
    }

    @Override
    public void delete(Integer id) throws RuntimeException {
        Long count = backendMemberDao.findMemberAndUserById(id);
        Order order = backendMemberDao.fingMemberOrderById(id);
        if(count > 0){
            //  会员关联了用户，先删除中间表，再删除会员表
            backendMemberDao.deleteMemberAndUserById(id);
        }

        if(order !=null ){
            throw new RuntimeException("当前会员已生成订单，不能删除");
        }

        backendMemberDao.deleteMember(id);

    }
}
